from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.database import get_db
from app.models.task import Task, TaskStatus
from app.schemas.task import TaskCreate, TaskUpdate, TaskInDB
from app.task_manager import TaskManager

router = APIRouter()


task_manager = TaskManager()


@router.post("/", response_model=TaskInDB, status_code=status.HTTP_201_CREATED)
async def create_task(
    task: TaskCreate,
    db: Session = Depends(get_db)
):
    """创建新的模糊测试任务"""
    try:
        db_task = await task_manager.create_task(db=db, task=task)
        return db_task
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.get("/", response_model=List[TaskInDB])
async def get_tasks(
    skip: int = 0,
    limit: int = 100,
    status: Optional[str] = None,
    db: Session = Depends(get_db)
):
    """获取任务列表"""
    filters = {}
    if status:
        filters["status"] = status
    tasks = await task_manager.get_tasks(db=db, skip=skip, limit=limit, **filters)
    return tasks


@router.get("/{task_id}", response_model=TaskInDB)
async def get_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """获取任务详情"""
    task = await task_manager.get_task(db=db, task_id=task_id)
    if not task:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Task {task_id} not found"
        )
    return task


@router.put("/{task_id}", response_model=TaskInDB)
async def update_task(
    task_id: int,
    task_update: TaskUpdate,
    db: Session = Depends(get_db)
):
    """更新任务信息"""
    task = await task_manager.update_task(db=db, task_id=task_id, task_update=task_update)
    if not task:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Task {task_id} not found"
        )
    return task


@router.delete("/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """删除任务"""
    success = await task_manager.delete_task(db=db, task_id=task_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Task {task_id} not found"
        )


@router.post("/{task_id}/start")
async def start_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """开始任务"""
    try:
        await task_manager.start_task(db=db, task_id=task_id)
        return {"message": "Task started successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post("/{task_id}/stop")
async def stop_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """停止任务"""
    try:
        await task_manager.stop_task(db=db, task_id=task_id)
        return {"message": "Task stopped successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post("/{task_id}/pause")
async def pause_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """暂停任务"""
    try:
        await task_manager.pause_task(db=db, task_id=task_id)
        return {"message": "Task paused successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post("/{task_id}/resume")
async def resume_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """恢复任务"""
    try:
        await task_manager.resume_task(db=db, task_id=task_id)
        return {"message": "Task resumed successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )